package br.com.controle.mdb;
 
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.Session;
import javax.naming.InitialContext;

@Stateless
@LocalBean
public class Mensagem {

    Connection connection = null;
    Session session = null;
    javax.jms.Queue destination = null;
        
    public Mensagem(){
         
    }
    

    public void sendJMSMessageToNotificationQueue(Object messageData) throws JMSException{

        try{            

            InitialContext init = new InitialContext();

            destination = (javax.jms.Queue) init.lookup("jms/NotificationQueue");
            ConnectionFactory connectionFactory = (ConnectionFactory) init.lookup("jms/NotificationQueueFactory");            
            
            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);                
            
            MessageProducer messageProducer = session.createProducer(destination);
            
            ObjectMessage tm = session.createObjectMessage();
            tm.setObject((Serializable) messageData);            
            
            messageProducer.send(tm);
        }  catch (Exception e){
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
        finally{
            if (session != null){
                try{
                    session.close();
                }
                catch (JMSException e){
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null){
                connection.close();
            }
        }
    }    
}